"""
ProjectName:qq_tools_bot 
FileName:message.py 
IdeaName:PyCharm 
UserName:zhao
UserMail:2909552840@qq.com
UserHomepage:https://www.zywi.cn
CreationTime:2024/10/30 下午2:13  
"""
import json
from typing import List

import requests
from pydantic import BaseModel
from typing import Optional

from models import Message
from utils import print_red, print_blue


class ResponseContent(BaseModel):
    """
    响应内容
    """
    # 状态
    status: Optional[str] = ''
    # 重新编码
    ret_code: Optional[int] = 0
    # 数据
    data: Optional[dict] = {}
    # message
    message: Optional[str] = ''
    # wording
    wording: Optional[str] = ''


class MessageApi:
    """
    消息API
    """

    def __init__(self, host: str, port: int, https: bool = False):
        super().__init__()
        # 服务器地址
        self.host = host
        # 服务器端口
        self.port = port
        # 服务器地址
        if https:
            self.url = f'https://{self.host}:{self.port}'
        else:
            self.url = f'http://{self.host}:{self.port}'

    def send_private_msg(self, user_id: int, message: List[Message]):
        """
        发送私聊消息
        :param user_id: QQ号
        :param message: 消息内容列表
        :return:
        """
        headers = {
            'Content-Type': 'application/json'
        }
        data = json.dumps({
            "user_id": user_id,
            "message": [json.loads(item.model_dump_json()) for item in message]
        })
        url = f"{self.url}/send_private_msg"
        response = requests.request("POST", url, headers=headers, data=data)
        if response.status_code != 200:
            print_red('SendPrivateMessageError:', response.text)
        else:
            res = ResponseContent(**response.json())
            print_blue('RequestResults:', res.model_dump_json())

    def send_group_msg(self, group_id: int, message: List[Message]):
        """
         发送群聊消息
        :param group_id: 群号
        :param message: 消息内容列表
        :return:
        """
        headers = {
            'Content-Type': 'application/json'
        }

        data = json.dumps({
            "group_id": group_id,
            "message": [json.loads(item.model_dump_json()) for item in message]
        })

        url = f"{self.url}/send_group_msg"
        response = requests.request("POST", url, headers=headers, data=data)
        if response.status_code != 200:
            print_red('SendGroupChatMessagesError:', response.text)
        else:
            res = ResponseContent(**response.json())
            print_blue('RequestResults:', res.model_dump_json())
